﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using WatiN.Core;

namespace Wateco.Core
{
    public class BrowserManager
    {
        private object browser;
        public T CreateBrowser<T>(Uri uri) {
            var browserObj = Convert.ChangeType(CreateBrowser(uri, typeof(T)),typeof(T), System.Globalization.CultureInfo.InvariantCulture);
            return (T) browserObj;
        }

        public Browser CreateBrowser(Uri uri, Type browserType) {
            switch (browserType.Name)
            {
				case "IE" :
                    return new IE(uri);
				case "FireFox" :
                    return new FireFox(uri);
            }
            return null;
        }

        public T GetBrowser<T>(Uri uri) {
            if (browser == null) {
				browser = CreateBrowser<T>(uri);
            }
			return (T)browser;
        }

		public void CloseBrowser<T>() {
			CloseBrowser(typeof(T));
		}

		public virtual void CloseBrowser(Type typeBrowser) {
			if (Convert.Equals(typeBrowser.Name.ToString(), "IE")) {
				var br = (IE)browser;
				if (br == null) return;
				br.Close();
				br = null;
				browser = null;
				if (IE.InternetExplorers().Count == 0) return;

				foreach (var explorer in IE.InternetExplorersNoWait()) {
					explorer.Close();
				}
				throw new Exception("Expected no open IE instances.");
			} else if (Convert.Equals(typeBrowser.Name.ToString(), "FireFox")) {
				var br = (FireFox)browser;
				if (br == null) return;
				br.Dispose();
				br = null;
				browser = null;
			}
		}
    }
}
